package model

import (
	. "api/util"
	"database/sql"
	"time"
	"errors"
	jwt "github.com/dgrijalva/jwt-go"
)

type (
	Syser struct {
		Id       string `json:"id"`
		Name     string `json:"name"`
		Password string `json:"password"`
	}
	IncomePay struct {
		Income int `json:"income"`
		Pay    int `json:"pay"`
	}
)

func (s *Syser) SyserLogin(name string, password string) (token string, err error) {
	sql1 := "SELECT * FROM syser WHERE name = ?"
	stmt, err := db.Prepare(sql1)
	if err != nil {
		return "", err
	}

	err = stmt.QueryRow(name).Scan(&s.Id, &s.Name, &s.Password)
	if err != nil && err != sql.ErrNoRows {
		return "", err
	}

	if err == sql.ErrNoRows || password != s.Password {
		return "", errors.New("用户名不存在或密码错误")
	}

	defer stmt.Close()

	tokenCliams := Claims{
        Id: 1,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: time.Now().Unix() + 24 * 3600000,
        },
    }

    token, err = MakeCliamsAdminToken(tokenCliams)

	return token, nil
}

func (i *IncomePay) GetIncomePay() (ret IncomePay, err error) {
	// 收入
	rows, err := db.Query("SELECT income FROM order_list ORDER BY id")
	if err != nil && err != sql.ErrNoRows {
		return ret, err
	}

	var totalIncome int
	for rows.Next() {
		var income int
		if err := rows.Scan(&income); err != nil {
			return ret, err
		}

		totalIncome += income
	}

	ret.Income = totalIncome
	defer rows.Close()

	// 支出
	rows1, err := db.Query("SELECT amount FROM withdraw WHERE status=2 ORDER BY id")
	if err != nil && err != sql.ErrNoRows {
		return ret, err
	}
	var totalPay int
	for rows1.Next() {
		var pw int
		if err := rows1.Scan(&pw); err != nil {
			return ret, err
		}

		totalPay += pw
	}
	ret.Pay = totalPay
	defer rows1.Close()

	rows2, err := db.Query("SELECT amount FROM charge WHERE status=2 ORDER BY id")
	if err != nil && err != sql.ErrNoRows {
		return ret, err
	}
	for rows2.Next() {
		var pc int
		if err := rows2.Scan(&pc); err != nil {
			return ret, err
		}

		totalPay += pc
	}
	ret.Pay = totalPay
	defer rows2.Close()

	return ret, err
}